package cn.magictodo.weblog.jwt.filter;

import cn.magictodo.weblog.common.enums.ResponseCodeEnum;
import cn.magictodo.weblog.common.utils.Response;
import cn.magictodo.weblog.jwt.handler.IPHandler;
import cn.magictodo.weblog.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liu
 * @since 2023-12-18 17:48
 */
@Slf4j
public class IPFilter extends OncePerRequestFilter {

    @Autowired
    private IPHandler ipHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!ipHandler.isLogin(request) && request.getRequestURI().contains("/login")) {
            ipHandler.failLogin(request);
            ResultUtil.fail(response, Response.fail(ResponseCodeEnum.LOGIN_TRY_OFTEN));
        }

        // 继续执行写一个过滤器
        filterChain.doFilter(request, response);
    }

}
